package com.example.controller;

import com.example.entity.po.Admin;
import com.example.utils.JWTUtils;
import com.example.utils.ResultUtils;
import com.example.service.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Controller
@RestController
public class AdminController {
    @Autowired
    private AdminService adminService;


    @PostMapping("/login")
    @ResponseBody
    public ResultUtils loginAdmin(@RequestBody Admin loginAdmin){
        //获取当前用户
        Subject subject= SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken UPtoken=new UsernamePasswordToken(loginAdmin.getAdminAccount(),loginAdmin.getAdminPwd());
        System.out.println("token:"+UPtoken.getCredentials());
        try {
            subject.login(UPtoken);
            System.out.println("成功");
            Map<String,String> payload=new HashMap<>();
            payload.put("adminAccount",loginAdmin.getAdminAccount());
            //生成JWT令牌
            String token= JWTUtils.getToken(payload);
            Map<String,Object> map=new HashMap<>();
            map.put("token",token);
            return ResultUtils.Successful("登录成功",map);
        }catch (UnknownAccountException e){
            System.out.println("用户名错误 ");
            return ResultUtils.Failure("用户名或密码错误",loginAdmin.getAdminAccount());
        }catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
            return ResultUtils.Failure("密码或密码错误",loginAdmin.getAdminAccount());
        }
    }

}
